﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace I_Authorization.Infrastructure
{
    /// <summary>
    /// 底层的仓储实现
    /// </summary>
    public class BaseRepository<T> : IRepository<T> where T : class, new()
    {
        private readonly EFDbContext _dbContext;

        public BaseRepository(EFDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task<int> AddAsync(T model)
        {
            await _dbContext.AddAsync(model);
            return await _dbContext.SaveChangesAsync();
        }

        public async Task<int> AddCountAsync(List<T> model)
        {
            await _dbContext.AddRangeAsync(model);
            return await _dbContext.SaveChangesAsync();
        }

        public async Task<int> AllStateDelete(List<T> list)
        {
            _dbContext.Set<T>().UpdateRange(list);
            return await _dbContext.SaveChangesAsync();
        }

        public async Task<int> DeleteAsync(int id)
        {
            var ids = await _dbContext.Set<T>().FindAsync(id);
            _dbContext.Set<T>().Remove(ids);
            return await _dbContext.SaveChangesAsync();
        }

        public async Task<int> DeleteAsync(T info)
        {
            _dbContext.Set<T>().Update(info);
            return await _dbContext.SaveChangesAsync();
        }

        public async Task<List<T>> GetAllAsync()
        {
           return await _dbContext.Set<T>().ToListAsync();
        }

        public async Task<List<T>> GetAsync(Expression<Func<T, bool>> expre)
        {
            return await _dbContext.Set<T>().Where(expre).ToListAsync();
        }

        public async Task<T> GetFindAsync(int id)
        {
            return await _dbContext.Set<T>().FindAsync(id);
        }
        public async Task<T> GetModelAsync(int id)
        {
            return await _dbContext.Set<T>().FindAsync(id);
        }

        public async Task<T> GetModelAsync(Expression<Func<T, bool>> expression)
        {
            return await _dbContext.Set<T>().FirstOrDefaultAsync(expression);
        }

        public async Task<int> UpdateAsync(T model)
        {
            _dbContext.Update(model);
            return await _dbContext.SaveChangesAsync();
        }

        public async Task<int> UpdateUpdAsync(List<T> list)
        {
            _dbContext.UpdateRange(list);
            return await _dbContext.SaveChangesAsync();
        }
    }
}
